from django.http import HttpResponseRedirect, HttpResponseServerError, HttpResponse
from django.utils import simplejson
from django.shortcuts import render_to_response

from .models import Note

def create(request):
    """
    """
    error_msg = u"No POST data sent."
    if request.method == "POST":
        post = request.POST.copy()
        if 'slug' in post and 'title' in post:
            slug = post['slug']
            if Note.objects.filter(slug=slug).count() > 0:
                error_msg = u"Slug already in use."
            else:
                title = post['title']
                new_note = Note.objects.create(title=title,slug=slug)
                return HttpResponseRedirect(new_note.get_absolute_url())
        else:
            error_msg = u"Insufficient POST data (need 'slug' and 'title'!)"
    return HttpResponseServerError(error_msg)

def update(request, slug):
    """
    """
    if request.method == "POST":
        post = request.POST.copy()
        note = Note.objects.get(slug=slug)
        if 'slug' in post:
            slug_str = post['slug']
            if note.slug != slug_str:
                if Note.objects.filter(slug=slug_str).count() > 0:
                    error_msg = u"Slug already taken."
                    return HttpResponseServerError(error_msg)
                note.slug = slug_str
        if 'title' in post:
            note.title = post['title']
        if 'text' in post:
            note.text = post['text']
        note.save()
        return HttpResponseRedirect(note.get_absolute_url())
    error_msg = u"No POST data sent."
    return HttpResponseServerError(error_msg)

def notejson(request):
    """
    """
    notejson.count += 1
    return HttpResponse(simplejson.dumps(dict(time=str(notejson.count))))
notejson.count = 0

def livepagejson(request):
    """
    """
    response = HttpResponse()
    response['Content-Type'] = 'text/javascript'
    response.write([dict(pk=int(o.pk), val=livepagejson.count) for o in Note.objects.all()])
    livepagejson.count += 1
    return response
livepagejson.count=0

def livepage(request):
    """
    """
    return render_to_response('notes/livepage.html', dict(note_list=Note.objects.all()))
 
